﻿using System;
using System.Data;

using System.Linq;
using WinnerCMS.Common;
using System.Collections.Generic;
using EntityFramework.Extensions;
using WinnerCMS.Model;
namespace WinnerCMS.Data
{
    /// <summary>
    /// DA_Guestbook 的摘要说明。
    /// </summary>
    public class GuestBookDal
    {
        /// <summary>
        /// 添加留言
        /// </summary>
        /// <param name="model"></param>
        public void Add(GuestBook model)
        {
            using (Entities db = new Entities())
            {
                db.GuestBooks.Add(model);
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 加载回复界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public GuestBook ReplyLoad(int id)
        {
            using (Entities db = new Entities())
            {
                return db.GuestBooks.FirstOrDefault(x => x.Id == id);
            }
        }
        /// <summary>
        /// 回复留言
        /// </summary>
        /// <param name="id"></param>
        /// <param name="reply"></param>
        public void PostReply(int id, string reply)
        {

            using (Entities db = new Entities())
            {
                var values = db.GuestBooks.FirstOrDefault(x => x.Id == id);
                values.Id = id;
                values.Reply = reply;
                db.SaveChangesAsync().Wait();

            }
        }
        /// <summary>
        /// 删除留言
        /// </summary>
        /// <param name="ids"></param>
        public void Delete(int[] ids)
        {
            using (Entities db = new Entities())
            {
                var q = db.GuestBooks.Where(x => ids.Contains(x.Id)).Delete();
 
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 删除指定IP的留言
        /// </summary>
        /// <param name="ip"></param>
        public void DeleteForIP(string ip)
        {

            using (Entities db = new Entities())
            {
                db.GuestBooks.Where(x => x.IP == ip).Delete();
                db.SaveChangesAsync().Wait();
            }
        }

        /// <summary>
        /// 绑定分页数据
        /// </summary>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<GuestBook> BindList(PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from u in db.GuestBooks select u;

                pp.RecordCount = query.Count();

                return query.OrderByDescending(x => x.UpdateTime).Skip(pp.Skip).Take(pp.PageSize).ToArray();
            }
        }
    }
}